<template>
  <div>
    <!-- 表单 -->
    <query-form @handleResetForm="handleResetForm" :formColumns="formColumns" v-model="formInline" @handleFormAction="handleFormAction"></query-form>
    <!-- 按钮 -->
    <div class="main-box">
      <div class="action">
        <el-button size="mini" type="primary" @click="openDialog">新增</el-button>
        <el-button size="mini" type="danger" v-has="'user-patch-delete'" @click="handleRemoveUser">批量删除</el-button>
      </div>
      <!-- 表格 -->
      <base-table :tree="{}" @handleSelectionChange="handleSelectionChange" @handleAction="handleAction" :tableData="tableData" @handleCurrentChange="handleCurrentChange" :pager="pager" :columns="columns"></base-table>
    </div>
    <Dialog :resertDialog="resertDialog" v-model="dialogForm" @handleSubmit="handleSubmit" :dialogColumns="dialogColumns"></Dialog>
  </div>
</template>

<script>
import Dialog from '../../components/common/Dialog.vue'
import BaseTable from '../../components/common/BaseTable.vue';
import userModel from '../../api/user.js';
import QueryForm from '../../components/common/QueryForm.vue';
import roleModel from '../../api/role.js'
import deptModel from '../../api/dept.js'

export default {
  data() {
    return {
      tableData: [],
      // 所有数据
      allList: [],
      // 表单内容
      formInline: {
        userId: '',
        userName: '',
        state: 0,
      },
      // 用户表单数据
      formColumns: {
        ref : "form",
        inline : true,
        size : "mini",
        columns:[
        {
          prop: 'userId',
          placeholder: '请输入用户ID',
          label: '用户ID',
          type: 'input',
        },
        {
          prop: 'userName',
          placeholder: '请输入用户名称',
          label: '用户名称',
          type: 'input',
        },
        {
          prop: 'state',
          type: 'select',
          label:'状态',
          option:[
            {value:0,label:'所有'},
            {value:1,label:'在职'},
            {value:2,label:'离职'},
            {value:3,label:'试用期'},
          ]
        },
        {
          type: 'action',
          list: [
            {
              action: 'search',
              size: 'mini',
              text: '查询',
              type: 'primary',
            },
            {
              action: 'reset',
              size: 'mini',
              text: '重置',
              type: 'default',
            },
          ],
        },
      ]
      },
      // 表格数据
      columns: [
        {
          type: 'selection',
          width: '55',
        },
        {
          label: '用户名',
          prop: 'userName',
        },
        {
          label: '用户邮箱',
          prop: 'userEmail',
        },
        {
          label: '用户角色',
          prop: 'role',
          formatter(row, column, value, index) {
            return { "0": '管理员', "1": '普通用户' }[value];
          },
        },
        {
          label: '用户状态',
          prop: 'state',
          formatter(row, column, value, index) {
            return {
              0: '所有',
              1: '在职',
              2: '离职',
              3: '试用期',
            }[value];
          },
        },
        {
          label: '注册时间',
          prop: 'lastLoginTime',
          formatter: (row, column, value, index) => this.dayjs(value).format('YYYY-MM-DD HH:mm:ss'),
        },
        {
          label: '最后登录时间',
          prop: 'lastLoginTime',
          formatter: (row, column, value, index) => this.dayjs(value).format('YYYY-MM-DD HH:mm:ss'),
        },
        {
          type: 'action',
          label: '操作',
          width: '150',
          list: [
            {
              text: '编辑',
              action: 'edit',
              size: 'mini',
              type: 'default',
            },
            {
              text: '删除',
              size: 'mini',
              type: 'danger',
              action: 'delete',
            },
          ],
        },
      ],
      // 分页数据
      pager: {
        pageNum: 1,
        pageSize: 5,
        total: 0,
      },
      // 弹出框
      dialogColumns:{
        title: '用户新增',
        dialogFormVisible: false,
         labelWidth : "80px",
        // size : "mini",
        columns:[
          {
            label: '用户名',
            type: 'text',
            prop: "userName",
            placeholder:"请输入用户名称"
          },
          {
            label: '邮箱',
            type: 'email',
            prop: "userEmail",
            placeholder:"请输入用户邮箱"
          },
          {
            label: '手机号',
            type: 'text',
            prop: "mobile",
            placeholder:"请输入手机号"
          },
          {
            label: '岗位',
            type: 'text',
            prop: "job",
            placeholder:"请输入岗位"
          },
          {
            label: '状态',
            type: 'select',
            prop: "state",
            placeholder:"请选择状态",
            options:[
              {value:1,label:'在职'},
              {value:2,label:'离职'},
              {value:3,label:'试用期'}
            ]
          },
          {
            label: '系统角色',
            type: 'select',
            prop: "roleList",
            placeholder: "请选择系统角色",
            options: []
          },
          {
            label : "部门",
            type : "cascader",
            prop : "deptId",
            placeholder : "请选择部门",
            options : []
          }
        ]
      },
      // 新增表单数据
      dialogForm:{},
      checkIdS:[],
      dialogstatus: false
    };
  },
  created() {
    this.getUserList()
  },
  watch: {
    dialogstatus:{
      handler(newvalue){
        if(newvalue) {
          this.initAlllist()
          this.initDeptList()
        }
    }
    }
  },
  methods: {
    // 获取用户角色数据
    async initAlllist(){
      const response = await roleModel.roleList()
      this.dialogColumns.columns.forEach(item => {
        if(item.prop==='roleList') {
          item.options = response.map(item=>{
            return {
              value: item._id,
              label: item.roleName
            }
          })
        }
      })
    },
    // 获取部分数据
    async initDeptList(){
      const response = await deptModel.deptList()
      this.dialogColumns.columns.forEach(item => {
        if(item.prop === 'deptId') {
          item.options = response
        }
      })
    },
    // 获取所有列表
    async getAllList() {
      const response = await userModel.getallList();
      console.log(response);
      this.allList = response;
    },
    // 获取列表
    async getUserList() {
      const obj = {
        pageNum: this.pager.pageNum,
        pageSize: this.pager.pageSize,
        ...this.formInline
      };
      const response = await userModel.getUserList(obj);
      this.tableData = response.list;
      this.pager.total = response.page.total;
    },
    handleSelectionChange() {},
    // 点击触发查询和重置事件
    handleFormAction(action){
      if(action == 'search') {
        this.handleSearch()
      }else{
        this.handleResetForm()
      }
    },
    // 查询事件
    handleSearch() {
      this.pager.pageNum = 1
      this.getUserList();
    },
    // 重置事件
    handleResetForm() {
      this.pager.pageNum = 1
      this.getUserList()
    },
    // 点击新增打开弹框
    openDialog() {
      this.dialogColumns.dialogFormVisible = true;
      this.dialogstatus = true
    },
    // 分页点击
    handleCurrentChange(val) {
      this.pager.pageNum = val;
      this.getUserList();
    },
    // 编辑
    handleEditDialog(row){
      this.dialogColumns.title = "用户编辑"

      this.dialogForm = {
        userName : row.userName,
        userEmail : row.userEmail,
        mobile : row.mobile,
        job : row.job,
        state : row.state,
        roleList : row.roleList[0],
        deptId : row.deptId,
        userId : row.userId
      }
      this.openDialog()
    },
    // 点击触发删除编辑事件
    handleAction({action,row}){
      if(action == 'delete'){
        this.handleRemoveUser(row.userId)
      }else if(action == 'edit') {
        this.handleEditDialog(row)
      }
    },
    // 删除
    async handleRemoveUser(userId){
      this.$confirm('确定删除此用户吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          console.log("111",this.checkIdS);
          this.checkIdS.push(userId)
          const response = await userModel.removeUser({userIds:this.checkIdS})
          this.getUserList()
          this.checkIdS = []
          this.$message({ type: 'success', message: '删除成功!'});
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消删除' });          
        });
    },
    // 批量删除
    handleSelectionChange(row){
      this.checkIdS = row.map((item,index) => item.userId)
    },
    // 子组件传过来的点击确定事件
    async handleSubmit(value){
      if(value === 'add') {
        this.dialogForm.action = 'add'
        const response = await userModel.addUser(this.dialogForm)
        this.dialogColumns.dialogFormVisible = false
        this.getUserList()
      }else if(value === 'edit'){
        this.dialogForm.action = 'edit'
        const response = await userModel.addUser(this.dialogForm)
        this.dialogColumns.dialogFormVisible = false
        console.log(this.dialogForm);
        this.getUserList()
      }
      this.resertDialog()
    },
    // 点击取消重置弹出框
    resertDialog(){
      this.dialogColumns.dialogFormVisible = false
       this.dialogForm = {
        userName : "",
        userEmail : "",
        mobile : "",
        job : "",
        state : "",
        roleList : "",
        deptId : "",
        userId : ""
      }
    }
  },
  components: {
    QueryForm,
    BaseTable,
    Dialog
  },
};
</script>

<style scoped>

</style>
